<template>
  <el-container class="home-wrapper">
    <el-header class="d-flex">
      <div class="logo d-center" @click="toggle">
        <i class="el-icon-menu"></i>
        <router-link to="/" style="display: block;"><h1 class="ml-3">博览社区</h1></router-link>
      </div>
      <div class="nav-box flex-1">
        <el-menu
          ref="headerMenu"
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="headerSelect"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-menu-item index="myCollection">我的收藏</el-menu-item>
          <el-menu-item index="1" @click="$router.push('/center/profile')">个人中心</el-menu-item>
        </el-menu>
      </div>
      <div class="rigth-menu">
        <el-dropdown>
          <span class="el-dropdown-link">
            {{ this.$store.state.username }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="$router.push('/center/profile')">个人中心</el-dropdown-item>
            <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>
    <el-container :class="showSidebar ? 'showSidebar' : ''" style="margin-top: 60px; background-color: #fff;">
      <!-- <el-drawer :visible.sync="drawer" :with-header="false" direction="ltr" size="200px"> -->
      <el-aside>
        <el-menu ref="sideMenu" :default-active="activeIndex2" class="el-menu-vertical-demo" @select="sideSelect">
          <el-menu-item index="all">全部业务</el-menu-item>
          <!-- <el-menu-item index="pay">充值说明</el-menu-item> -->
          <!-- 一级菜单 -->
          <template v-for="item in menuList">
            <el-submenu v-if="item.children.length > 0" :index="item.id" :key="item.id">
              <template slot="title">
                <span>{{ item.label }}</span>
              </template>
              <!-- 二级菜单 -->
              <el-menu-item :index="subItem.id" v-for="subItem in item.children" :key="subItem.id">
                {{ subItem.label }}
              </el-menu-item>
            </el-submenu>
            <el-menu-item v-else :index="item.id" :key="item.id">{{ item.label }}</el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <div class="mask" v-show="showMask" @click="closeSidebar"></div>
      <!-- </el-drawer> -->
      <el-main>
        <div>
          <div v-show="all">
            <div class="broadcast fs14 mb-1 d-flex">
              <i class="iconfont icon-guangbo mr-1 "></i>
              <div v-html="broadcast"></div>
            </div>
            <div class="notice fs16" v-html="notice"></div>
          </div>
          <div v-show="collectedGoods.length === 0 && myCollection" class="fs-2">暂无内容</div>
          <div v-show="goodsOnDisplay.length === 0 && !myCollection" class="fs-2">暂无内容</div>
          <ul class="goods d-flex flex-wrap">
            <li v-for="item in goodsOnDisplay" :key="item.id" v-show="!myCollection">
              <div class="item">
                <img v-lazy="item.image" />
                <div class="collect-btn" :class="item.favorites ? 'active' : ''" @click="handelCollect(item)"></div>
                <div class="name center ellipsis-m fs16 bold">{{ item.name }}</div>
                <div class="btn center">
                  <el-button type="danger" size="small" round @click="goDetail(item)">立即购买</el-button>
                </div>
              </div>
            </li>

            <li v-for="item in collectedGoods" :key="item.id" v-show="myCollection">
              <div class="item">
                <img v-lazy="item.image" />
                <div class="collect-btn" :class="item.favorites ? 'active' : ''" @click="cancelCollect(item)"></div>
                <div class="name center ellipsis-m fs16 bold">{{ item.name }}</div>
                <div class="btn center">
                  <el-button type="danger" size="small" round @click="goDetail(item)">立即购买</el-button>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import GetCateList from "@/utils/productCate";
import lf from "localforage";
export default {
  data() {
    return {
      broadcast: "",
      notice: "",
      showSidebar: false,
      showMask: false,
      all: true, // 是否为全部业务
      myCollection: false, // 是否进入收藏页
      activeName: "myCollection",
      activeIndex: "", //头部导航激活索引
      activeIndex2: "all", //侧边栏导航激活索引  不管 activeIndex 设置成什么，最终的属性还是指向 activeIndex
      currentGoods: "", // 当前查看的商品
      goods: [
        // 所有商品
        // {
        //   id: '',
        //   collected: false,
        //   cate: "onList",
        //   img: "https://s3.ax1x.com/2021/02/06/yYQ1S0.png",
        //   title: "名字名字名字名字名字名字名字名字名字",
        // },
      ],
      goodsOnDisplay: [], // 展示的商品
      collectedGoods: [], // 收藏的商品
      menuList: [],
      goodsList: [],
    };
  },

  created() {
    this.init();
    this.getMenuList();
    this.fetch();
    this.getSysInfo("broadcast");
    this.getSysInfo("notice");
  },

  methods: {
    init() {
      this.goodsOnDisplay = this.goods;
      this.myCollection = false;
      this.all = true;
    },
    async getSysInfo(key) {
      const formData = new FormData();
      formData.append("label_key", key);
      const { data: res } = await this.$http.post("findSysInfoByKey", formData);
      if (res.code != "0") return this.$message("获取系统信息失败");
      this[key] = res.data.label_content;
    },
    // 获取所有的菜单
    async getMenuList() {
      const parentList = await GetCateList();
      // console.log(parentList, "处理后的菜单");
      this.menuList = parentList;
    },
    //获取商品列表
    async fetch() {
      // 获取通过审核的商品
      const formData = new FormData();
      formData.append("page", 1);
      formData.append("rows", 1000);
      const { data: res } = await this.$http.post("productList", formData);
      // console.log(res, "通过审核且商品状态正常");
      if (res.code != "0") return this.$message("获取商品失败！");

      this.goods = this.goodsOnDisplay = res.data;
      await lf.setItem("goods", res.data);
    },
    async fetchFavorites() {
      const { data: res } = await this.$http.post("productFavoritesList");
      // console.log(res, "收藏的商品");
      if (res.code != "0") return this.$message("获取收藏商品列表失败");
      res.data.result.forEach((item) => {
        item.favorites = true;
      });
      this.collectedGoods = res.data.result;
    },
    // 到商品详情页
    goDetail(item) {
      this.$router.push(`/center/order/${item.id}`);
    },
    // 取消收藏
    cancelCollect(item) {
      this.$confirm("确认要取消收藏这种商品吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const formData = new FormData();
          formData.append("productId", item.product_id);
          const { data: res } = await this.$http.post("productFavorites", formData);
          // console.log(res);
          if (res.code != "0") return this.$message("操作失败");
          this.$message.success("取消成功");
          this.fetchFavorites();
          this.fetch();
        })
        .catch(() => {});
    },
    // 点击收藏或取消收藏
    async handelCollect(item) {
      // console.log(item);
      if (!item.favorites) {
        const formData = new FormData();
        formData.append("productId", item.id);
        const { data: res } = await this.$http.post("productFavorites", formData);
        if (res.code != "0") return this.$message("收藏失败");
        item.favorites = true;
        this.$message.success("收藏成功");
      } else {
        const formData = new FormData();
        formData.append("productId", item.id);
        const { data: res } = await this.$http.post("productFavorites", formData);
        if (res.code != "0") return this.$message("收藏失败");
        item.favorites = false;
        this.$message("已取消收藏");
      }
    },
    // 头部导航菜单事件
    async headerSelect(index) {
      // 直接改变 this.activeIndex 值，不起作用，故采用下面的方法
      this.$refs.sideMenu.activeIndex = "";
      if (index == "myCollection") {
        // 进入收藏页
        this.all = false;
        this.myCollection = true;
        this.fetchFavorites();
      }
    },
    // 侧边栏导航菜单事件
    sideSelect(index, indexPath) {
      this.toggle();
      this.myCollection = false;
      this.activeName = "";
      this.$refs.headerMenu.activeIndex = "";

      // console.log(this.goods, "所有商品");
      if (index == "all") {
        this.all = true;
        this.goodsOnDisplay = this.goods;
      } else {
        this.all = false;
        this.goodsOnDisplay = this.goods.filter((item) => item.category_id == index);
      }
    },
    logout() {
      this.$store.commit("Logout");
      if (this.$store.state.token) return this.$message("退出失败");

      this.$router.push("/login");
      this.$message.success("退出成功");
    },

    toggle() {
      if (window.innerWidth > 1250) return;
      this.showSidebar = !this.showSidebar;
      this.showMask = !this.showMask;
    },
    closeSidebar() {
      if (window.innerWidth > 1250) return;
      this.showSidebar = false;
      this.showMask = false;
    },
  },
};
</script>

<style lang="scss">
.home-wrapper {
  .el-header {
    .logo {
      i {
        display: none;
      }
    }

    .rigth-menu {
      width: 200px;
    }
  }
  .mask {
    position: fixed;
    left: 0px;
    right: 0px;
    top: 0px;
    bottom: 0px;
    height: 100%;
    width: 100%;
    background-color: #000;
    opacity: 0.4;
    z-index: 80;
  }
  .el-main {
    padding: 25px 100px 100px;
    .broadcast {
      padding: 15px;
      border: 2px solid blue;
      border-radius: 20px;
      i {
        font-size: 20px;
        color: #ffa500;
      }
    }
    .notice {
      padding: 20px;
      border: 2px dashed #ffa500;
      border-radius: 15px;
    }
  }
  .nav-box {
    margin-left: 20px;
    .el-menu-item {
      margin-right: 50px;
    }
  }
}

.goods {
  li {
    width: 25%;
    padding: 20px;
    .item {
      position: relative;
      padding-top: 135%;
      // background-size: 100% 100%;
      img {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
      }
      .collect-btn {
        position: absolute;
        top: 0;
        left: 6%;
        width: 16%;
        height: 17%;
        border: 0px solid red;
      }
      .active {
        background-color: red;
        opacity: 0.5;
      }
      .name {
        padding: 0 22px;
        width: 100%;
        text-align: center;
        top: 60%;
      }
      .btn {
        top: 86%;
        text-align: center;
      }
    }
  }
}

@media screen and (max-width: 1250px) {
  .home-wrapper {
    .el-header {
      min-width: 100%;
      .logo {
        width: auto;
        flex: 1;
        i {
          display: block;
          font-size: 24px;
        }
      }
      .nav-box {
        margin-left: 0;
        .el-menu-item {
          margin-right: 0;
        }
      }
      .rigth-menu {
        flex: 1;
        width: auto;
      }
    }
    .el-aside {
      left: -200px;
    }
    .showSidebar {
      .el-aside {
        left: 0;
      }
    }
    .el-main {
      margin-left: 0px;
      padding: 20px;
    }
  }
}
@media screen and (max-width: 750px) {
  .home-wrapper {
    .el-header {
      .logo {
        width: 50px;
        flex: none;
        h1 {
          display: none;
        }
      }
      .nav-box {
        .el-menu-item {
          padding: 0 5px;
        }
      }
      .rigth-menu {
        flex: none;
        width: 110px !important;
        margin-right: 10px;
      }
    }
    .showSidebar {
      .el-aside {
        left: 0;
      }
    }
    .goods li {
      width: 50%;
      padding: 20px;
      .item {
        .btn {
          .el-button {
            padding: 7px 15px;
          }
        }
      }
    }
  }
}
</style>
